import { formatDateTime } from './utils'

export default function (sqlite) {
  return {
    // 插入日志
    insertLogger(msg) {
      return new Promise((resolve, reject) => {
        const sql = 'INSERT INTO logger (logger_msg,create_time) VALUES (?,?)'
        sqlite.run(sql, [msg, formatDateTime()], function (err) {
          if (err) {
            console.error('Error inserting logger:', err.message)
            reject(err.message)
          } else {
            resolve(this.lastID)
          }
        })
      })
    },

    // 获取日志
    getLogger(pageSize, offset) {
      return new Promise((resolve, reject) => {
        // 获取日志数据（分页，倒序）
        const sql = 'SELECT * FROM logger ORDER BY logger_id DESC LIMIT ? OFFSET ?'
        sqlite.all(sql, [pageSize, offset*pageSize], (err, rows) => {
          if (err) {
            console.error('Error fetching logger:', err.message)
            reject(err.message)
          } else {
            // 获取总记录数
            const countSql = 'SELECT COUNT(*) AS total FROM logger'
            sqlite.get(countSql, [], (err, countRow) => {
              if (err) {
                console.error('Error fetching total count:', err.message)
                reject(err.message)
              } else {
                // 返回日志数据和总记录数
                resolve({
                  rows, // 当前页的数据
                  total: countRow.total // 总记录数
                })
              }
            })
          }
        })
      })
    }
  }
}
